package com.wp.file.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wp.file.common.BaseContext;
import com.wp.file.common.exception.MyTokenException;
import com.wp.file.common.R;
import com.wp.file.utils.JwtTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * 判断用户是否token授权
 */
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        R<Object> result = null;
        try {
            //拿到请求头中的的token
            String auth = request.getHeader("Authorization");
            log.info(auth);
            if(StringUtils.isBlank(auth)){
                throw new MyTokenException("用户暂未登录");
            }
            DecodedJWT decodedJWT = JwtTool.parseJWT(auth);//解析验证token 解析不出来就会报错
            String userId = decodedJWT.getClaims().get("userId").asString();
            BaseContext.setCurrentId(Long.valueOf(userId));
            log.info(userId);
            return true;
        } catch (MyTokenException e){
            e.printStackTrace();
            result = R.error(e.getMessage());
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            result = R.error("签名无效");
        } catch (TokenExpiredException e){
            e.printStackTrace();
            result = R.error("token过期");
        } catch (AlgorithmMismatchException e){
            e.printStackTrace();
            result = R.error("token算法不同");
        } catch (Exception e){
            e.printStackTrace();
            result = R.error("token无效");
        }
        /**
         * 转为json数据
         */
        String json = new ObjectMapper().writeValueAsString(result);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(json);
        return false;
    }
}
